<template>
  <el-table
    :data="filterTableData"
    style="width: 100%; margin-bottom: 20px"
    row-key="id"
    :tree-props="{ children: 'children' }"
  >
    <el-table-column type="expand">
      <template #default="props">
        <el-table
          :data="props.row.children"
          style="width: 100%; margin-bottom: 20px"
          row-key="id"
          :tree-props="{ children: 'children' }"
          :show-header="false"
        >
          <el-table-column type="expand">
            <template #default="props">
              <el-table
                :data="props.row.children"
                style="width: 100%; margin-bottom: 20px"
                row-key="id"
                :tree-props="{ children: 'children' }"
                :show-header="false"
              >
                <el-table-column prop="id" label="序号" />
                <el-table-column prop="name" label="课程/章节/题目" />
                <el-table-column>
                  <template #default="scope">
                    <el-button
                      size="large"
                      type="success"
                      @click="handleComplete(scope.row)"
                      :disabled="scope.row.ispass"
                      >一键完成</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </el-table-column>
          <el-table-column prop="id" label="序号" />
          <el-table-column prop="name" label="课程/章节/题目" />
          <el-table-column>
            <template #default="scope">
              <el-button
                size="large"
                type="primary"
                @click="handleChapterComplete(scope.row)"
                :disabled="scope.row.isChaperPass"
                >一键全部完成</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </template>
    </el-table-column>

    <el-table-column prop="id" label="序号" />
    <el-table-column prop="name" label="课程/章节/题目" />
    <el-table-column align="right"></el-table-column>
    <el-table-column>
      <template #header>
        <el-input
          v-model="search"
          :prefix-icon="Search"
          width="20"
          size="large"
          clearable
          class="w-50 m-2"
          placeholder="请输入关键词"
        />
      </template>
    </el-table-column>
  </el-table>
  <div class="ind">
    <el-button type="danger" @click="exit()" :icon="ArrowLeft"
      >退出当前账号</el-button
    >
  </div>
</template>
<script>
import { ref, computed } from "vue";
import { useMainStore } from "../store/index.js";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import axios from "axios";
import { Search, ArrowLeft } from "@element-plus/icons-vue";
export default {
  name: "Main",
  setup() {
    const mainStore = useMainStore();
    let search = ref("");
    var TableData = [];
    const router = useRouter();
    let token = localStorage.getItem("loginfo");
    axios
      .get("/education/api/Student/GetStudentInfo", {
        headers: { authorization: "Bearer " + token },
      })
      .then((value) => {
        if (value.data.data.stuInfo.classID) {
          mainStore.saveClassID(value.data.data.stuInfo.classID);
        } else {
          ElMessage({
            showClose: true,
            message: "请重新登录",
            center: true,
            type: "error",
          });
          useRouter().push("/login");
          localStorage.removeItem("loginfo");
        }
      });
    function getChapters(i, id) {
      axios
        .get(
          `/evaluation/api/studentevaluate/GetCourseInfoByCourseId?CourseID=${id}`,
          {
            headers: { authorization: "Bearer " + token },
          }
        )
        .then((value) => {
          for (let j in value.data.data.chapters) {
            let minchildren = new Array(
              value.data.data.chapters[j].knowledgeList.length
            );
            let isPassList = new Array(
              value.data.data.chapters[j].knowledgeList.length
            );
            for (let index in value.data.data.chapters[j].knowledgeList) {
              value.data.data.chapters[j].knowledgeList[index].testMemberInfo !=
              null
                ? (isPassList[index] =
                    value.data.data.chapters[j].knowledgeList[index]
                      .testMemberInfo.isPass == true
                      ? true
                      : false)
                : false;

              minchildren[index] = {
                id: `${i}${j}${index}`,
                name: value.data.data.chapters[j].knowledgeList[index]
                  .knowledge,
                ispass: isPassList[index],
                knowlegid: value.data.data.chapters[j].knowledgeList[index].id,
              };
            }
            let count = 0;
            for (let c of isPassList) {
              if (c == true) {
                count++;
              }
            }
            TableData[i].children[j] = {
              id: `${i}${j}`,
              name: `${value.data.data.chapters[j].title},${value.data.data.chapters[j].titleContent}`,
              children: minchildren,
              isChaperPass: count == isPassList.length ? true : false,
            };
          }
        });
    }
    function data() {
      if (token == null || token == "undefined") {
        useRouter().push("/login");
      } else {
        axios
          .get("/evaluation/api/stuevaluatereport/GetLatestCourse?", {
            headers: { authorization: "Bearer " + token },
          })
          .then(
            (value) => {
              if (value.data.msg == "无效的登录凭证，请重新登录") {
                ElMessage({
                  showClose: true,
                  message: "请重新登录",
                  center: true,
                  type: "error",
                });
                useRouter().push("/login");
                localStorage.removeItem("loginfo");
              } else {
                for (let i in value.data.data) {
                  TableData[i] = {
                    id: i,
                    name: value.data.data[i].CourseName,
                    children: new Array(value.data.data[i].ChapterCount),
                  };
                  getChapters(i, value.data.data[i].ID);
                }
                ElMessage({
                  showClose: true,
                  message: "获取数据成功",
                  center: true,
                  type: "success",
                });
                mainStore.getData(TableData);
              }
            },
            (err) => {}
          );
      }
    }
    data();
    const filterTableData = computed(() =>
      mainStore.Data.filter(
        (data) =>
          !search.value ||
          data.name.toLowerCase().includes(search.value.toLowerCase())
      )
    );
    function dohh(knowlegid, data) {
      axios
        .get(
          `/evaluation/api/studentevaluate/beginevaluate?kpId=${knowlegid}`,
          {
            headers: { authorization: "Bearer " + token },
          }
        )
        .then((value) => {
          if (
            value.data.msg ==
            "距你上次评估这个知识点还没有10分钟，再多准备准备吧！"
          ) {
            ElMessage({
              type: "error",
              message: "不能重复点,10分钟为间隔,",
            });
          } else if (value.data.msg == "您已经评估过3次了") {
            ElMessage({
              type: "error",
              message: "你已经做过三次了，不能在做了",
            });
          } else if (value.data.msg == "您已经通过该知识点") {
            ElMessage({
              type: "success",
              message: "你刚刚已经做完了这个",
            });
          } else {
            axios
              .post(
                "/evaluation/api/studentevaluate/SaveEvalutionQuestion",
                data,
                {
                  headers: { authorization: "Bearer " + token },
                }
              )
              .then((value) => {
                if (
                  value.data.data.isPass == true ||
                  value.data.data.errorCount == 0
                ) {
                  ElMessage({
                    showClose: true,
                    message: "完毕成功~~",
                    center: true,
                    type: "success",
                  });
                } else {
                  ElMessage({
                    showClose: true,
                    message: "错误",
                    center: true,
                    type: "error",
                  });
                }
              });
          }
        });
    }
    function doComplete(knowlegid) {
      axios
        .get(
          `/evaluation/api/TeacherEvaluation/GetKnowQuestionEvaluation?classID=${mainStore.classID}&knowledgeID=${knowlegid}`,
          {
            headers: { authorization: "Bearer " + token },
          }
        )
        .then((value1) => {
          let answerIDList = new Array();
          for (let i = 0; i <= value1.data.data.length - 1; i++) {
            axios
              .get(
                `/evaluation/api/TeacherEvaluation/GetQuestionAnswerListByQID?classID=${mainStore.classID}&questionID=${value1.data.data[i].QuestionID}`,
                {
                  headers: { authorization: "Bearer " + token },
                }
              )
              .then((value) => {
                let answerArr = [];
                for (let j of value.data.data) {
                  if (j.isTrue == true) {
                    answerArr.push(j.id);
                  }
                }
                answerIDList[i] = {
                  QuestionID: value1.data.data[i].QuestionID,
                  AnswerID: answerArr.join(","),
                };
                if (answerIDList.length == value1.data.data.length) {
                  dohh(knowlegid, {
                    kpid: knowlegid,
                    questions: answerIDList,
                  });
                }
              });
          }
        });
    }
    function complete(obj) {
      axios
        .post(
          "/api/createOrder",
          { amount: 0.3, payType: 4, count: 1 },
          {
            headers: {
              "Content-Type": "application/json",
              askKey:
                "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhcHBJZCI6ODEyNTQwNjQyNjk5MzMzNjMyLCJnZXRNYW5hZ2VtZW50SWQiOjc3Nzg0NjU4NjIxNjEwODAzMiwiVElNRSI6MTY4MjgzNjM5NTczNH0.l65YhJtp4fJoMddKxwj7UVubmhxtO4mx5E6y8Pdij10",
            },
          }
        )
        .then((value) => {
          if (
            value.data.message ==
            "当前IP5分钟内创建未支付订单超过5个,请支付后或等待5分钟后重试"
          ) {
            ElMessage({
              type: "error",
              message: "求求你不要多次申请o(╥﹏╥)o,我耐不住,在等5分钟后试试",
            });
          } else {
            axios
              .post(
                "/api/pay",
                { orderNo: value.data.data.orderNO },
                {
                  headers: {
                    "Content-Type": "application/json",
                    askKey:
                      "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhcHBJZCI6ODEyNTQwNjQyNjk5MzMzNjMyLCJnZXRNYW5hZ2VtZW50SWQiOjc3Nzg0NjU4NjIxNjEwODAzMiwiVElNRSI6MTY4MjgzNjM5NTczNH0.l65YhJtp4fJoMddKxwj7UVubmhxtO4mx5E6y8Pdij10",
                  },
                }
              )
              .then((value) => {
                // console.log(value.data.data.code);
                // console.log(value.data.data);
                // if (value.data.data.code) {
                ElMessage({
                  type: "error",
                  message: "注意不要过度频繁，没有二维码就重试",
                });
                // } else {
                ElMessageBox.confirm(
                  "<h2>微信支付</h2><img src=" + value.data.data.code + ">",
                  "支付界面(3毛钱)",
                  {
                    confirmButtonText: "已支付",
                    cancelButtonText: "取消支付",
                    type: "info",
                    center: true,
                    dangerouslyUseHTMLString: true,
                  }
                )
                  .then(() => {
                    axios
                      .post(
                        "/api/searchOrder",
                        { orderNo: value.data.data.orderNo },
                        {
                          headers: {
                            "Content-Type": "application/json",
                            askKey:
                              "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhcHBJZCI6ODEyNTQwNjQyNjk5MzMzNjMyLCJnZXRNYW5hZ2VtZW50SWQiOjc3Nzg0NjU4NjIxNjEwODAzMiwiVElNRSI6MTY4MjgzNjM5NTczNH0.l65YhJtp4fJoMddKxwj7UVubmhxtO4mx5E6y8Pdij10",
                          },
                        }
                      )
                      .then((value) => {
                        if (value.data.data.state == 1) {
                          ElMessage({
                            type: "success",
                            message: "支付成功",
                          });
                          doComplete(obj.knowlegid);
                        } else if (value.data.data.state == 4) {
                          ElMessage({
                            type: "error",
                            message:
                              "检测到你没有支付，如果有问题请联系:QQ631759716",
                          });
                        }
                      });
                  })
                  .catch(() => {
                    ElMessage({
                      type: "info",
                      message: "取消订单成功",
                    });
                  });
                // }
              });
          }
        });
    }
    return {
      search,
      mainStore,
      filterTableData,
      ArrowLeft,
      Search,
      handleComplete(obj) {
        complete(obj);
      },
      handleChapterComplete() {},
      exit() {
        ElNotification({
          title: "Success",
          message: "退出当前账号成功",
          type: "success",
        });
        localStorage.removeItem("loginfo");
        router.replace("/login");
      },
    };
  },
};
</script>
<style scoped>
.ind {
  position: fixed;
  left: 20px;
  top: 20px;
  z-index: 1000;
}
</style>
